package at.codebase.web.servlets.user;

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import at.codebase.core.log.Log;
import at.codebase.db.dao.EApiPartnerDao;
import at.codebase.db.dao.EItemDao;
import at.codebase.db.entities.EApiPartner;
import at.codebase.db.entities.EItem;
import at.codebase.db.entities.EUser;
import at.codebase.security.SecureStringBuilder;
import at.codebase.web.servlets.user.UserDelete.AccountDeleteHelper;
import at.codebase.web.templates.MainTemplate;
import at.codebase.web.templates.UserProfileTemplate;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters;
import at.codebase.web.util.URLParameters.ParameterDoesNotExistException;
import at.codebase.web.util.URLParameters.ParameterParsingException;
import at.codebase.web.util.api.ApiPartnerCalls;
import at.codebase.web.util.json.JsonEncoder;
import at.codebase.web.util.json.JsonEncoder.TransferSettings;
import at.codebase.web.util.json.JsonEncoder.TransferSettings.MailTransfer;
import at.codebase.web.util.template.Template;
import at.codebase.web.util.template.TemplateEngine;

import com.google.appengine.api.users.UserServiceFactory;

public class UserTransfer extends AUserProfile {
	
	@Override
	void buildUserPage(MainTemplate mainTemplate, UserProfileTemplate userProfileTemplate, RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		EUser user = requestInfo.getUser();
		
		boolean error = false;
		String errorMessage = null;
		
		
		if(user != null){
			if(requestType.equals(RequestType.GET)){
				buildPage(mainTemplate, userProfileTemplate, requestInfo, error, errorMessage);
			}else{
				try {
					String randomKeyInput = requestInfo.getParameters().getString("randomKey");
					if(useToken(randomKeyInput)){
						
						URLParameters parameters = requestInfo.getParameters();
						EApiPartner apiPartner = null;
						
						try {
							apiPartner = EApiPartnerDao.getApiPartner(new Long(parameters.getLong("ex_destination")));
						} catch (ParameterParsingException e) { }
						
						if(apiPartner != null){
						
							boolean exportDescription = false;
							boolean exportItems = false;
							try{
								String ex_items = parameters.getString("ex_items");
								if(ex_items.equals("true"))
									exportItems = true;
							}catch(ParameterDoesNotExistException e){ }
							
							try{
								String ex_items = parameters.getString("ex_description");
								if(ex_items.equals("true"))
									exportDescription = true;
							}catch(ParameterDoesNotExistException e){ }
							
							
							String ex_username = parameters.getString("ex_username");
							String exportUsername = ex_username;
							
							String ex_mail = parameters.getString("ex_mail");
							MailTransfer exportMail = MailTransfer.USER_MAIL;
							if(ex_mail.equals("nomail"))
								exportMail = MailTransfer.EXAMPLE_MAIL;
							
							
							TransferSettings transferSettings = new TransferSettings(exportUsername, exportMail, exportDescription, exportItems);
							
							JSONObject jsonResult = transferUseraccount(apiPartner, requestInfo.getUser(), transferSettings);
							
							if(jsonResult != null && jsonResult.get("success").equals(new Boolean(true))){
								//DELETE ACCOUNT
								AccountDeleteHelper.delete(user);
								Log.logUser(requestInfo.getUser().getId(),
										"User (userId=" + user.getId() + ", googleId="
												+ user.getGoogleUserId()
												+ ") transferred his account to "+apiPartner.getAppName());
								redirectTo(UserServiceFactory.getUserService().createLogoutURL("/newest"));
							}else{
								error = true;
								if(jsonResult != null){
									errorMessage = (String) jsonResult.get("message");	
								}
							}
							
						}

						buildPage(mainTemplate, userProfileTemplate, requestInfo, error, errorMessage);
							
					}else{
						buildPage(mainTemplate, userProfileTemplate, requestInfo, error, errorMessage);
					}

				} catch (ParameterDoesNotExistException e) {
					buildPage(mainTemplate, userProfileTemplate, requestInfo, error, errorMessage);
				}
			}
		
		}
	}
	
	private void buildPage(MainTemplate mainTemplate, UserProfileTemplate userProfileTemplate, RequestInformation requestInfo, boolean error, String errorMessage) {
		mainTemplate.setTitle("Transfer Account");
		Template userDeleteT = TemplateEngine.getTemplate("user/site_profile_transfer.html");
		
		String options = "";
		List<EApiPartner> partnerList = EApiPartnerDao.getApiPartnerList();
		for(EApiPartner partner:partnerList){
			options += "<option value=\""+partner.getPartnerId()+"\">"+partner.getAppName()+"</option>";
		}
		userDeleteT.setHTML("partnerOptionList", options);
		
		if(error){
			SecureStringBuilder sb = new SecureStringBuilder();
			sb.appendSecure(errorMessage);
			userDeleteT.setHTML("errorMessage", "<h3 style=\"color:red;\">Sorry, an error occurred.</h3><p style=\"color:red;\">"+sb.toString()+"</p>");	
		}
		
		userDeleteT.setText("username", requestInfo.getUser().getUsername());
		userDeleteT.setText("usermail", requestInfo.getUser().getMail());	
		
		userDeleteT.setText("randomKey", nextToken());
		userProfileTemplate.setContent(userDeleteT);
	}
	
	public static JSONObject transferUseraccount(EApiPartner partner, EUser user, TransferSettings transferSettings){
		
		ArrayList<EItem> items = EItemDao.getItemsBySeller(user.getId());
		JSONObject userTransferObj = JsonEncoder.encodeUser(user, items, transferSettings);
		
		String call = "&user_data="+userTransferObj.toJSONString();

		String result = ApiPartnerCalls.makeApiCall(partner, "/webservices/user_import", call, "POST");

		JSONObject jsonResult = (JSONObject) JSONValue.parse(result);

		return jsonResult;
		
				
	}
		
}